import React, { useState, useEffect } from 'react';
import {
  Box,
  Table,
  TableBody,
  TableCell,
  TableContainer,
  TableHead,
  TableRow,
  Paper,
  IconButton,
  Chip,
  Typography,
  Button,
  Dialog,
  DialogTitle,
  DialogContent,
  DialogActions,
  TextField,
  FormControl,
  InputLabel,
  Select,
  MenuItem,
  Switch,
  FormControlLabel,
  Alert,
  Tooltip,
  Pagination,
  Stack,
  InputAdornment,
  FormGroup,
  Checkbox,
  FormControlLabel as MuiFormControlLabel,
  Grid,
} from '@mui/material';
import { DataGrid, GridColDef } from '@mui/x-data-grid';
import { Iconify } from 'src/components/iconify';
import {
  getRules,
  updateRule,
  deleteRule,
  toggleRuleStatus,
} from 'src/api/auto-accounting';
import { AutoAccountingBatchActions } from './auto-accounting-batch-actions';
import AddIcon from '@mui/icons-material/Add';
import { AutoAccountingRuleCreateDialog } from './auto-accounting-rule-create-dialog';

interface AutoAccountingRule {
  id: string;
  ruleName: string;
  ruleType: string;
  description: string;
  amount: number;
  frequency: string;
  isActive: boolean;
  priority: number;
  createTime: string;
  updateTime: string;
  nextExecuteTime: string;
  executeCount: number;
}

interface PageInfo {
  list: AutoAccountingRule[];
  pageNum: number;
  pageSize: number;
  total: number;
  pages: number;
  hasNextPage: boolean;
  hasPreviousPage: boolean;
}

export function AutoAccountingRuleList({ refreshTrigger }: { refreshTrigger: number }) {
  const [rules, setRules] = useState<AutoAccountingRule[]>([]);
  const [loading, setLoading] = useState(false);
  const [message, setMessage] = useState('');
  const [severity, setSeverity] = useState<'success' | 'error' | 'info' | 'warning'>('info');
  const [editDialogOpen, setEditDialogOpen] = useState(false);
  const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
  const [createDialogOpen, setCreateDialogOpen] = useState(false);
  const [selectedRule, setSelectedRule] = useState<AutoAccountingRule | null>(null);
  const [editForm, setEditForm] = useState<Partial<AutoAccountingRule>>({});
  
  // 分页状态
  const [pageInfo, setPageInfo] = useState<PageInfo>({
    list: [],
    pageNum: 1,
    pageSize: 10,
    total: 0,
    pages: 0,
    hasNextPage: false,
    hasPreviousPage: false,
  });
  
  // 搜索和过滤状态
  const [searchTerm, setSearchTerm] = useState('');
  const [ruleTypeFilter, setRuleTypeFilter] = useState<string>('');
  const [statusFilter, setStatusFilter] = useState<string>('');
  const [sortBy, setSortBy] = useState<string>('createTime');
  const [sortOrder, setSortOrder] = useState<string>('DESC');

  const columns: GridColDef[] = [
    {
      field: 'ruleName',
      headerName: '规则名称',
      flex: 1.5,
      sortable: true,
    },
    {
      field: 'ruleType',
      headerName: '规则类型',
      flex: 1,
      sortable: true,
      renderCell: (params) => {
        const typeMap: { [key: string]: { label: string; color: string } } = {
          EXPENSE: { label: '支出', color: 'error' },
          INCOME: { label: '收入', color: 'success' },
          TRANSFER: { label: '转账', color: 'info' },
        };
        const typeInfo = typeMap[params.value] || { label: params.value, color: 'default' };
        return <Chip label={typeInfo.label} color={typeInfo.color as any} size="small" />;
      },
    },
    {
      field: 'description',
      headerName: '描述',
      flex: 2,
      sortable: false,
    },
    {
      field: 'amount',
      headerName: '金额',
      type: 'number',
      flex: 1,
      sortable: true,
    },
    {
      field: 'frequency',
      headerName: '执行频率',
      flex: 1,
      sortable: false,
    },
    {
      field: 'isActive',
      headerName: '状态',
      flex: 1,
      sortable: true,
      renderCell: (params) => (
        <Switch
          checked={params.value}
          onChange={() => handleToggleStatus(params.row)}
          size="small"
        />
      ),
    },
    {
      field: 'nextExecuteTime',
      headerName: '下次执行时间',
      flex: 1.5,
      sortable: true,
      valueFormatter: (params: any) =>
        params.value ? new Date(params.value as string).toLocaleString('zh-CN') : '-',
    },
    {
      field: 'actions',
      headerName: '操作',
      type: 'actions',
      width: 120,
      getActions: (params) => [
        <Tooltip title="编辑">
          <IconButton onClick={() => openEditDialog(params.row as AutoAccountingRule)}>
            <Iconify icon="eva:edit-fill" />
          </IconButton>
        </Tooltip>,
        <Tooltip title="删除">
          <IconButton onClick={() => openDeleteDialog(params.row as AutoAccountingRule)}>
            <Iconify icon="eva:trash-2-outline" />
          </IconButton>
        </Tooltip>,
      ],
    },
  ];

  // 批量操作状态
  const [selectedRules, setSelectedRules] = useState<string[]>([]);

  // 获取规则列表
  const fetchRules = async (page = 1, size = 10) => {
    try {
      setLoading(true);
      const params = new URLSearchParams({
        pageNumber: page.toString(),
        pageSize: size.toString(),
        sortBy: sortBy,
        sortOrder: sortOrder,
      });
      
      if (searchTerm) params.append('ruleName', searchTerm);
      if (ruleTypeFilter) params.append('ruleType', ruleTypeFilter);
      if (statusFilter) params.append('isActive', statusFilter);
      
      const result = await getRules(params);
      
      if (result.code === '00000') {
        const pageData = result.data.data;
        setRules(pageData.list || []);
        setPageInfo({
          ...pageData,
        });
        setMessage('规则列表加载成功');
        setSeverity('success');
      } else {
        setMessage(result.message || '获取规则列表失败');
        setSeverity('error');
      }
    } catch (error) {
      console.error('Error fetching rules:', error);
      setMessage('获取规则列表失败');
      setSeverity('error');
    } finally {
      setLoading(false);
    }
  };

  // 处理分页变化
  const handlePageChange = (event: React.ChangeEvent<unknown>, page: number) => {
    fetchRules(page, pageInfo.pageSize);
  };

  // 处理搜索
  const handleSearch = () => {
    fetchRules(1, pageInfo.pageSize);
  };

  // 处理排序
  const handleSort = (field: string) => {
    const newOrder = sortBy === field && sortOrder === 'ASC' ? 'DESC' : 'ASC';
    setSortBy(field);
    setSortOrder(newOrder);
    fetchRules(1, pageInfo.pageSize);
  };

  // 更新规则
  const handleUpdateRule = async () => {
    if (!selectedRule || !editForm.id) return;
    
    try {
      setLoading(true);
      const result = await updateRule(editForm.id, editForm);
      
      if (result.code === '00000') {
        setMessage('规则更新成功');
        setSeverity('success');
        setEditDialogOpen(false);
        fetchRules(pageInfo.pageNum, pageInfo.pageSize);
      } else {
        setMessage(result.message || '更新规则失败');
        setSeverity('error');
      }
    } catch (error) {
      console.error('Error updating rule:', error);
      setMessage('更新规则失败');
      setSeverity('error');
    } finally {
      setLoading(false);
    }
  };

  // 删除规则
  const handleDeleteRule = async () => {
    if (!selectedRule) return;
    
    try {
      setLoading(true);
      const result = await deleteRule(selectedRule.id);
      
      if (result.code === '00000') {
        setMessage('规则删除成功');
        setSeverity('success');
        setDeleteDialogOpen(false);
        fetchRules(pageInfo.pageNum, pageInfo.pageSize);
      } else {
        setMessage(result.message || '删除规则失败');
        setSeverity('error');
      }
    } catch (error) {
      console.error('Error deleting rule:', error);
      setMessage('删除规则失败');
      setSeverity('error');
    } finally {
      setLoading(false);
    }
  };

  // 切换规则状态
  const handleToggleStatus = async (rule: AutoAccountingRule) => {
    try {
      const result = await toggleRuleStatus(rule.id);
      
      if (result.code === '00000') {
        fetchRules(pageInfo.pageNum, pageInfo.pageSize);
      } else {
        setMessage(result.message || '切换状态失败');
        setSeverity('error');
      }
    } catch (error) {
      console.error('Error toggling rule status:', error);
      setMessage('切换状态失败');
      setSeverity('error');
    }
  };

  // 打开编辑对话框
  const openEditDialog = (rule: AutoAccountingRule) => {
    setSelectedRule(rule);
    setEditForm(rule);
    setEditDialogOpen(true);
  };

  // 打开删除对话框
  const openDeleteDialog = (rule: AutoAccountingRule) => {
    setSelectedRule(rule);
    setDeleteDialogOpen(true);
  };

  // 处理选择单个规则
  const handleSelectRule = (ruleId: string, checked: boolean) => {
    setSelectedRules(prev => {
      if (checked) {
        return [...prev, ruleId];
      } else {
        return prev.filter(id => id !== ruleId);
      }
    });
  };

  // 处理选择所有规则
  const handleSelectAll = (checked: boolean) => {
    if (checked) {
      setSelectedRules(rules.map(rule => rule.id));
    } else {
      setSelectedRules([]);
    }
  };

  // 批量操作成功后的回调
  const handleBatchSuccess = () => {
    fetchRules(pageInfo.pageNum, pageInfo.pageSize);
  };

  useEffect(() => {
    // 只在refreshTrigger > 0时才自动加载，避免页面打开就执行
    if (refreshTrigger > 0) {
      fetchRules(1, 10);
    }
  }, [refreshTrigger]);

  // 添加一个手动加载的方法
  const handleManualLoad = () => {
    fetchRules(1, 10);
  };

  if (loading && rules.length === 0) {
    return (
      <Box textAlign="center" py={4}>
        <Typography>加载中...</Typography>
      </Box>
    );
  }

  return (
    <Box>
      {message && (
        <Alert severity={severity} sx={{ mb: 2 }} onClose={() => setMessage('')}>
          {message}
        </Alert>
      )}

      {/* 批量操作组件 */}
      <AutoAccountingBatchActions rules={rules} onSuccess={() => fetchRules(pageInfo.pageNum, pageInfo.pageSize)} />

      {/* 搜索和过滤区域 */}
      <Box sx={{ mb: 3 }}>
        <Grid container spacing={2} alignItems="center">
          <Grid item xs={12} md={3}>
            <TextField
              fullWidth
              size="small"
              placeholder="搜索规则名称..."
              value={searchTerm}
              onChange={(e) => setSearchTerm(e.target.value)}
              onKeyPress={(e) => e.key === 'Enter' && handleSearch()}
              InputProps={{
                startAdornment: (
                  <InputAdornment position="start">
                    <Iconify icon="eva:search-fill" />
                  </InputAdornment>
                ),
              }}
            />
          </Grid>
          <Grid item xs={12} md={2}>
            <FormControl fullWidth size="small">
              <InputLabel>规则类型</InputLabel>
              <Select
                value={ruleTypeFilter}
                onChange={(e) => setRuleTypeFilter(e.target.value)}
                label="规则类型"
              >
                <MenuItem value="">全部</MenuItem>
                <MenuItem value="EXPENSE">支出</MenuItem>
                <MenuItem value="INCOME">收入</MenuItem>
                <MenuItem value="TRANSFER">转账</MenuItem>
              </Select>
            </FormControl>
          </Grid>
          <Grid item xs={12} md={2}>
            <FormControl fullWidth size="small">
              <InputLabel>状态</InputLabel>
              <Select
                value={statusFilter}
                onChange={(e) => setStatusFilter(e.target.value)}
                label="状态"
              >
                <MenuItem value="">全部</MenuItem>
                <MenuItem value="true">启用</MenuItem>
                <MenuItem value="false">禁用</MenuItem>
              </Select>
            </FormControl>
          </Grid>
          <Grid item xs={12} md={2}>
            <Button
              fullWidth
              variant="contained"
              onClick={handleSearch}
              startIcon={<Iconify icon="eva:search-fill" />}
            >
              搜索
            </Button>
          </Grid>
          <Grid item xs={12} md={3}>
            <Button
              fullWidth
              variant="outlined"
              onClick={handleManualLoad}
              startIcon={<Iconify icon="eva:refresh-fill" />}
            >
              加载规则
            </Button>
          </Grid>
          <Grid item xs={12} md={2}>
            <Button
              fullWidth
              variant="contained"
              onClick={() => setCreateDialogOpen(true)}
              startIcon={<AddIcon />}
              color="primary"
            >
              新建规则
            </Button>
          </Grid>
        </Grid>
      </Box>

      {/* 规则列表表格 */}
      <Box sx={{ height: 650, width: '100%' }}>
        <DataGrid
          rows={rules}
          columns={columns}
          rowCount={pageInfo.total}
          loading={loading}
          pageSizeOptions={[5, 10, 20]}
          paginationMode="server"
          getRowId={(row) => row.id || `rule-${row.ruleName || Math.random()}`}
          onPaginationModelChange={(model) => fetchRules(model.page + 1, model.pageSize)}
          onSortModelChange={(model) => {
            if (model.length > 0) {
              handleSort(model[0].field);
            } else {
              handleSort('createTime');
            }
          }}
          checkboxSelection
          onRowSelectionModelChange={(selection) => {
            setSelectedRules(selection as string[]);
          }}
          rowSelectionModel={selectedRules}
        />
      </Box>


      {/* 分页控制 */}
      {pageInfo.pages > 1 && (
        <Box display="flex" justifyContent="center" mt={3}>
          <Pagination
            count={pageInfo.pages}
            page={pageInfo.pageNum}
            onChange={handlePageChange}
            color="primary"
            showFirstButton
            showLastButton
          />
        </Box>
      )}

      {/* 分页信息 */}
      <Box display="flex" justifyContent="space-between" alignItems="center" mt={2}>
        <Typography variant="body2" color="text.secondary">
          共 {pageInfo.total} 条记录，第 {pageInfo.pageNum} 页，共 {pageInfo.pages} 页
        </Typography>
        <Box display="flex" gap={1}>
          <Button
            size="small"
            disabled={!pageInfo.hasPreviousPage}
            onClick={() => fetchRules(pageInfo.pageNum - 1, pageInfo.pageSize)}
          >
            上一页
          </Button>
          <Button
            size="small"
            disabled={!pageInfo.hasNextPage}
            onClick={() => fetchRules(pageInfo.pageNum + 1, pageInfo.pageSize)}
          >
            下一页
          </Button>
        </Box>
      </Box>

      {/* 编辑对话框 */}
      <Dialog open={editDialogOpen} onClose={() => setEditDialogOpen(false)} maxWidth="md" fullWidth>
        <DialogTitle>编辑规则</DialogTitle>
        <DialogContent>
          <Grid container spacing={2} sx={{ mt: 1 }}>
            <Grid item xs={12} md={6}>
              <TextField
                fullWidth
                label="规则名称"
                value={editForm.ruleName || ''}
                onChange={(e) => setEditForm({ ...editForm, ruleName: e.target.value })}
              />
            </Grid>
            <Grid item xs={12} md={6}>
              <FormControl fullWidth>
                <InputLabel>规则类型</InputLabel>
                <Select
                  value={editForm.ruleType || ''}
                  onChange={(e) => setEditForm({ ...editForm, ruleType: e.target.value })}
                  label="规则类型"
                >
                  <MenuItem value="EXPENSE">支出</MenuItem>
                  <MenuItem value="INCOME">收入</MenuItem>
                  <MenuItem value="TRANSFER">转账</MenuItem>
                </Select>
              </FormControl>
            </Grid>
            <Grid item xs={12}>
              <TextField
                fullWidth
                label="描述"
                value={editForm.description || ''}
                onChange={(e) => setEditForm({ ...editForm, description: e.target.value })}
                multiline
                rows={3}
              />
            </Grid>
            <Grid item xs={12} md={6}>
              <TextField
                fullWidth
                label="金额"
                type="number"
                value={editForm.amount || 0}
                onChange={(e) => setEditForm({ ...editForm, amount: parseFloat(e.target.value) })}
              />
            </Grid>
            <Grid item xs={12} md={6}>
              <TextField
                fullWidth
                label="优先级"
                type="number"
                value={editForm.priority || 3}
                onChange={(e) => setEditForm({ ...editForm, priority: parseInt(e.target.value) })}
                inputProps={{ min: 1, max: 5 }}
              />
            </Grid>
          </Grid>
        </DialogContent>
        <DialogActions>
          <Button onClick={() => setEditDialogOpen(false)}>取消</Button>
          <Button onClick={handleUpdateRule} variant="contained" disabled={loading}>
            更新
          </Button>
        </DialogActions>
      </Dialog>

      {/* 创建规则对话框 */}
      <AutoAccountingRuleCreateDialog
        open={createDialogOpen}
        onClose={() => setCreateDialogOpen(false)}
        onSuccess={() => {
          setCreateDialogOpen(false);
          fetchRules(pageInfo.pageNum, pageInfo.pageSize);
        }}
      />

      {/* 删除确认对话框 */}
      <Dialog open={deleteDialogOpen} onClose={() => setDeleteDialogOpen(false)}>
        <DialogTitle>确认删除</DialogTitle>
        <DialogContent>
          <Typography>
            确定要删除规则 "{selectedRule?.ruleName}" 吗？此操作不可撤销。
          </Typography>
        </DialogContent>
        <DialogActions>
          <Button onClick={() => setDeleteDialogOpen(false)}>取消</Button>
          <Button onClick={handleDeleteRule} color="error" variant="contained" disabled={loading}>
            删除
          </Button>
        </DialogActions>
      </Dialog>
    </Box>
  );
}
